<!-- 参与班级 -->
<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { useUserInfoStore } from '@/store/userInfo'
import { fetchMyClassListAPI } from '@/apis/fetchMyClassList'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<Class>>(
  fetchClasses,
  { isNoMore: d => d?.list.length === d?.total },
)

const displayedList = computed(() => {
  return dataList.value.filter(el => el.id && el.images && el.title)
})

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

async function fetchClasses(d?: LoadMoreData<Class>): Promise<LoadMoreData<Class>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchMyClassListAPI({
    page: _page.toString(),
    limit: '20',
  }, userInfoStore.userInfo!.token!)

  return {
    list: res?.data?.data.data || [],
    page: _page,
    total: res?.data?.data.total || 9999,
  }
}

onReachBottom(() => loadMore())

function handleTapClassCard(id: string) {
  router.push({
    name: 'classHome',
    params: { id },
  })
}
</script>

<template>
  <Spacer height="36" />
  <view class="grid grid-cols-2 gap-20rpx">
    <ClassCard
      v-for="c in displayedList"
      :key="c.id"
      :picture="withDomain(c.images) || ''"
      :title="c.title"
      :author="c.place"
      :created-at="c.start_time"
      @tap="handleTapClassCard(c.id.toString())"
    />
  </view>
  <!-- 加载更多 -->
  <uv-load-more v-if="displayedList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  <Spacer height="80" />
  <PageDefault v-if="displayedList.length === 0">
    暂无课程
  </PageDefault>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'myClasses'
style:
  navigationBarTitleText: '参与班级'
  onReachBottomDistance: 100
</route>
